package com.backwaveweibo.bww.controller;

import com.backwaveweibo.bww.entity.User;
import com.backwaveweibo.bww.service.UserService;
import com.backwaveweibo.bww.utils.*;
import com.jn.sqlhelper.dialect.pagination.PagingResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    UserService userService;


    /**
     * 注册接口
     *
     * @param user
     * @return
     */


    @PostMapping("register")
    public Result register(@RequestBody User user) {
        Boolean data = userService.addUser(user);
        return new Result().setCode(data?ResultCode.SUCCESS:ResultCode.FAIL).setMessage(data?"注册成功":"注册失败");

    }

    /**
     * 登录接口
     *
     * @param response
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        log.info(String.valueOf(user));
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        log.info("认证前 " + subject.isAuthenticated());
        subject.login(usernamePasswordToken);
        log.info("认证后" + subject.isAuthenticated());
        if (subject.isAuthenticated()) {
            User loginUser = (User) subject.getPrincipal();
            String token = JwtTokenUtil.createJWT(loginUser.getUserId(), loginUser.getUsername(), loginUser.getType());
            response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY, JwtTokenUtil.TOKEN_PREFIX + token);
            // 这是Header其中一个属性向外暴露，使得他能被浏览器js读取
            response.setHeader("Access-Control-Expose-Headers", JwtTokenUtil.AUTH_HEADER_KEY);
            return new Result().setMessage("登陆成功").setData(loginUser.setPassword("无可奉告")).setCode(ResultCode.SUCCESS);

        }
        return new Result().setCode(ResultCode.FAIL);

    }

    /**
     * 单查接口
     *
     * @param user
     * @return
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @GetMapping("find")
    public Result getUser(User user) {
        return new Result().setData(userService.findUser(user)).setCode(ResultCode.SUCCESS);
    }

    /**
     * 更新用户接口
     *
     * @param user 要更改的用户实体
     * @param file 要更改的用户头像
     * @return
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @PostMapping("update")
    public Result updateUser(User user, @RequestParam(value = "file", required = false) MultipartFile file) {
        log.info("获取到的user: {}", user);
        log.info("是否能获取到文件==> {}", file != null);
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            log.info("文件名:" + originalFilename);
            try {
                InputStream inputStream = file.getInputStream();
                String photo = FileUploadWithQiNiuYun.uploadQNImg((FileInputStream) inputStream, originalFilename);
                user.setPhoto(photo);
            } catch (IOException e) {
                log.error("上传文件错误",e);
            }
        }
        Boolean updateUser = userService.updateUser(user);
        User findUser = userService.findUser(new User().setUserId(user.getUserId()));
        findUser.setPassword("嘤嘤嘤");
        return new Result().setMessage(updateUser?"更改成功":"更改失败").setData(findUser).setCode(updateUser?ResultCode.SUCCESS:ResultCode.FAIL);
    }

    /**
     * 更改密码接口
     * ##@param id 要更改密码的用户id
     * ##@param originalPassword  原密码
     * ##@param newPassword 新密码
     *
     * @return
     */
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @PostMapping("updatePassword")
    public Result adminUpdateUser(@RequestBody Map<String, String> map) {
        String originalPassword = map.get("originalPassword");
        String newPassword = map.get("newPassword");
        User user = JwtTokenUtil.getUser();
        Boolean data = userService.updatePassword(user.getUserId(), originalPassword, newPassword);
        return new Result().setCode(data?ResultCode.SUCCESS:ResultCode.FAIL).setMessage(data?"更改成功":"更改失败");
    }

    /**
     * 删除用户接口
     *
     * @param userId
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("delete")
    public Result deleteUser(Long userId) {
        Boolean data = userService.deleteUser(userId);
        return new Result().setData(data).setMessage("删除" + (data ? "成功" : "失败")).setCode(data ? ResultCode.SUCCESS : ResultCode.FAIL);
    }

    /**
     * 分页数据
     *
     * @param pageNumber 页码
     * @param pageSize   每页大小
     * @param user       查询条件
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping("userpage")
    public Result findUserPage(Integer pageNumber, Integer pageSize, User user) {
        PagingResult userPage = userService.findUserPage(pageNumber, pageSize, user);
        return new Result().setData(userPage);
    }

    /**
     * 未授权页面
     *
     * @return
     */
    @GetMapping("unauthorized")
    public Result unauthorized() {
        return new Result().setMessage("您没有这个权限哦亲");
    }
}
